package com.xs.langchain4j_springboot.service;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;

@Service
public class DownLoadFileService {
    public void downloadFileFromOss(String url, Path outputPath) throws IOException, InterruptedException {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .build();

        HttpResponse<Path> response = client.send(request, HttpResponse.BodyHandlers.ofFile(outputPath));
        if (response.statusCode() != 200) {
            throw new RuntimeException("Download failed with status code: " + response.statusCode());
        }
        System.out.println("File downloaded to: " + outputPath);
    }

    public String readDocument(Path filePath) throws IOException {
        String fileName = filePath.toString().toLowerCase();
        if (fileName.endsWith(".pdf")) {
            return readPdf(filePath);
        } else {
            throw new UnsupportedOperationException("Unsupported file type: " + fileName);
        }
    }

    private static String readPdf(Path filePath) throws IOException {
        PDDocument document = PDDocument.load(filePath.toFile());
        PDFTextStripper stripper = new PDFTextStripper();
        String text = stripper.getText(document);
        document.close();
        return text;
    }

}
